<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class LoginForm extends CFormModel {

    public $username;
    public $password;
    public $rememberMe;

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules() {
        return array(
            // username and password are required
            array('username', 'required', 'message' => '请输入用户名'),
            array('password', 'required', 'message' => '请输入密码'),
            // rememberMe needs to be a boolean
            array('rememberMe', 'boolean'),
            // password needs to be authenticated
            array('password', 'authenticate'),
        );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels() {
        return array(
            'rememberMe' => '记住登录状态',
            'username' => '用户名',
            'password' => '密&#12288;码',
        );
    }

    /**
     * 验证密码是否正确
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute, $params) {
        if (!$this->hasErrors()) {
            $userInfo = Yii::app()->user->getLocalUser($this->username, $this->password);
            if ($userInfo == false) {
                $this->addError('password', '用户名和密码不匹配.');
            } else {
                return true;
            }
        }
    }

    /**
     * 用户登录
     * @return type
     */
    public function login() {
        if (Yii::app()->user->login($this->username, $this->password, $this->rememberMe ? 604800 : 86400)) {
            return true;
        }
        $this->addError('', Yii::app()->user->getError() ? Yii::app()->user->getError() : '登录失败！');
        return false;
    }

}
